package com.lowca.news.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.compass.core.util.StringUtils;
import org.springframework.stereotype.Repository;

import com.lowca.news.dao.ArticleDao;
import com.lowca.news.dao.support.Pager;
import com.lowca.news.entity.Article;
import com.lowca.news.entity.Category;
import com.lowca.news.web.formbean.AdminArticleConditionForm;

@Repository
public class ArticleDaoImpl extends BaseDaoImpl<Article, Long> implements
		ArticleDao {

	@Override
	public Pager<Article> searchArticle(AdminArticleConditionForm condition,
			int pageNo, int pageSize) {
		List<Object> params = new ArrayList<Object>();
		StringBuffer sb = new StringBuffer("select a from Article a where 1=1");
		if (condition != null) {
			if (StringUtils.hasText(condition.getSubject())) {
				sb.append(" and a.subject like ?");
				params.add("%" + condition.getSubject() + "%");
			}
			if (StringUtils.hasText(condition.getSummary())) {
				sb.append(" and a.summary like ?");
				params.add("%" + condition.getSummary() + "%");
			}
			if (condition.getPublishTimeMin() != null) {
				sb.append(" and a.publishTime>=?");
				params.add(condition.getPublishTimeMin());
			}
			if (condition.getPublishTimeMax() != null) {
				sb.append(" and u.publishTime<=?");
				params.add(condition.getPublishTimeMax());
			}

			if (condition.getCategoryId() != null) {
				Category c = getHibernateTemplate().get(Category.class,
						condition.getCategoryId());
				sb.append(" and a.category=?");
				params.add(c);
			}
		}
		sb.append(" order by a.publishTime desc");
		return super.findPageByHQL(pageNo, pageSize, sb.toString(),
				params.toArray());
	}
}
